package com.huanxun.engine;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

/**
 * 登录
 * 
 */
public class LoginEngine {
	public static String loginUseHttpClientByPost(String path,Map<String,String> map) throws Exception{
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(path);
		
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		for(Map.Entry<String, String> entry:map.entrySet()){
			String name = entry.getKey();
			String value = entry.getValue();
			NameValuePair nvp = new BasicNameValuePair(name, value);
			parameters.add(nvp);
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
		request.setEntity(entity);
		
		HttpResponse response = client.execute(request);
		if(response.getStatusLine().getStatusCode() == 200){
			InputStream inputStream = response.getEntity().getContent();
			
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len = inputStream.read(buffer)) != -1){
				bos.write(buffer, 0, len);
			}
			String result = bos.toString();
			bos.close();
			inputStream.close();
			return result;
	}
		return "";
}
}